package com.jkc.xh.network;

import android.content.Intent;

import com.jkc.xh.MainApplication;
import com.jkc.xh.activities.LoginActivity_;
import com.jkc.xh.manager.UserManager;
import com.jkc.xh.network.models.ResponseEntity;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.utils.L;

import java.io.IOException;

import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * Created by wangjie28 on 2015/10/30.
 */
public abstract class RestCallBack<T> implements Callback<ResponseEntity<T>> {

    public abstract void success(T t);

    public abstract void failure(RestError error);

    @Override
    public void onResponse(Response<ResponseEntity<T>> response, Retrofit retrofit) {

        if (response.isSuccess()) {
            int code = response.body().code;
            if (code == 0) {
                success(response.body().data);
            } else {
                if (code == 1003) {
                    UserManager.clearLoginInfo();
                    //TODO  android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag.
                    MainApplication.getInstance().getBaseContext().startActivity(new Intent(MainApplication.getInstance().getBaseContext(), LoginActivity_.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                failure(new RestError(response.body().code, response.body().msg));
            }
        } else {
            try {
                String errorMsg = response.errorBody().string();
//                Gson gson = new Gson();
//                RestError error = gson.fromJson(errorMsg, RestError.class);
                failure(new RestError(response.code(), errorMsg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
        L.e(t, "retrofit onFailure");
//        failure(new RestError(-1, "网络异常"));
//        failure(new RestError(-1, t.getMessage()));
    }
}
